package com.bluesmart.mia;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.sys.Constants;
import com.sys.DemoApp;
import com.util.Constant;
import com.util.ImageLoaderHelper;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.util.Utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class AccountActivity extends BaseActivity implements OnClickListener{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_account);
		
		((TextView) findViewById(R.id.center)).setText(getString(R.string.account));
		((Button) findViewById(R.id.right)).setCompoundDrawablesWithIntrinsicBounds(0, 0,
				R.drawable.a01, 0);
		
        ((EditText) findViewById(R.id.text0)).setText(PreferencesUtils.getString(this, "nickname"));
        ((TextView) findViewById(R.id.text1)).setText(PreferencesUtils.getString(this, "username"));
        ((EditText) findViewById(R.id.text2)).setText(PreferencesUtils.getString(this, "password_src"));
        
        ImageLoaderHelper.displayImage(R.drawable.a37, (ImageView)findViewById(R.id.icon), 
        		PreferencesUtils.getString(this, "userimg"));
		
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);
		findViewById(R.id.text3).setOnClickListener(this);
		findViewById(R.id.text4).setOnClickListener(this);
		findViewById(R.id.text5).setOnClickListener(this);
		findViewById(R.id.icon).setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		switch(arg0.getId())
		{
		case R.id.left:
			finish();
			break;
			
		case R.id.right:
			sendHttpGetRequest();
			break;
			
		case R.id.icon:
			showImagePicker();
			break;
			
		case R.id.text3:
		{
			Intent intent = new Intent(this,BabyListActivity.class);
			startActivity(intent);
			break;
		}
			
		case R.id.text4:
		{
			Intent intent = new Intent(this,PrivacyActivity.class);
			intent.putExtra("flag", "0");
			startActivity(intent);
			break;
		}
			
		case R.id.text5:
			showQuerySearch();
			break;
		}
	}
	
	void showQuerySearch() {
		final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_query);
		mDialog.findViewById(R.id.left).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
					}
				});
		mDialog.findViewById(R.id.right).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						sendLogutRequest();
						mDialog.dismiss();
					}
				});
		((TextView)mDialog.findViewById(R.id.content)).setText(getString(R.string.logout_tip));
		mDialog.show();
	}
	
	private void sendHttpGetRequest() {
		final String nickname = ((EditText) findViewById(R.id.text0)).getText().toString();
		final String password = ((EditText) findViewById(R.id.text2)).getText().toString();
		
		if(nickname.length() == 0 || password.length() == 0)
		{
			ToastUtil.showToastWithAlertPic(R.string.all_info);
			return;
		}
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					ToastUtil.showToastWithAlertPic(R.string.success);

					PreferencesUtils.putString(getApplicationContext(), "password", Utils.Md5(password));
					PreferencesUtils.putString(getApplicationContext(), "nickname", nickname);
					PreferencesUtils.putString(getApplicationContext(), "password_src", password);
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else 
				{
				}
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", Utils.Md5(password));
		params.put("nickname", nickname);
		params.put("handType", "update");

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/Account.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	private void sendLogutRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					PreferencesUtils.putString(getApplicationContext(), "nickname","");
					PreferencesUtils.putString(getApplicationContext(), "username","");
					PreferencesUtils.putString(getApplicationContext(), "is_login", "0");
					PreferencesUtils.putString(getApplicationContext(), "password","");
					PreferencesUtils.putString(getApplicationContext(), "userimg", "");
					
					List<Activity> list = ((DemoApp)getApplicationContext()).getActivityList();
					for(Activity item:list) item.finish();
					
					startActivity(new Intent(AccountActivity.this,LoginActivity.class));
					finish();
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else 
				{
				}
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("deviceid", "");

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/Logout.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	void showImagePicker()
	{
		final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		
		OnClickListener listen = new OnClickListener()
		{
			@Override
			public void onClick(View arg0) {
				if(arg0.getId() == R.id.cancel) mDialog.dismiss();
				else if(arg0.getId() == R.id.pic)
				{
					mDialog.dismiss();
					Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
					getAlbum.setType("image/*");
					startActivityForResult(getAlbum, 3);
				}
				else
				{
					mDialog.dismiss();
					Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
					startActivityForResult(intent, 4);
				}
			}
		};

		mDialog.setContentView(R.layout.dialog_img_choose);
		mDialog.findViewById(R.id.camera).setOnClickListener(listen);
		mDialog.findViewById(R.id.pic).setOnClickListener(listen);
		mDialog.findViewById(R.id.cancel).setOnClickListener(listen);
		mDialog.show();
	
	}
	
	private File mPhotoFile;
	@SuppressWarnings({ "deprecation" })
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;

		Bitmap bitmap = null;
		if (resultCode == RESULT_OK) {
			if (requestCode == 4) {
				Uri uri = data.getData();
				if (uri != null) {
					bitmap = BitmapFactory.decodeFile(uri.getPath());
				}

				if (bitmap == null) {
					Bundle bundle = data.getExtras();
					if (bundle != null) {
						bitmap = (Bitmap) bundle.get("data");
					}
				}
			} else if (requestCode == 3) {
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				bitmap = Utils
						.getImageThumbnail(cursor.getString(column_index));
			}

			if (bitmap == null)
				return;
			
			mPhotoFile = new File(Constants.PIC_PATH);// 将要保存图片的路径
			mPhotoFile.deleteOnExit();
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(mPhotoFile));
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			sendHttpImgRequest(bitmap);
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void sendHttpImgRequest(final Bitmap bitmap) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					((ImageView) findViewById(R.id.icon)).setImageBitmap(bitmap);
					ToastUtil.showToastWithAlertPic(R.string.success);
					
					((DemoApp)getApplicationContext()).sendLoginRequest();
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else
				{
				}
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		try {
			params.put("filename", mPhotoFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		MgqRestClient.post(Constant.SERVER_URL + "/sw/uploadimg.ashx", params, loginHandler);
	}
}
